package com.example.music_liwei.fragment;

import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.example.music_liwei.R;
import com.example.music_liwei.adapter.LyricsAdapter;
import com.example.music_liwei.bean.ResponseData;
import com.example.music_liwei.messageEvent.MessageEventSeekbar;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

public class BlankFragmentDesc extends Fragment {

    private RecyclerView rvLyrics;
    private LyricsAdapter lyricsAdapter;
    private LinearLayoutManager layoutManager;
    private List<LyricsLine> lyricsLines = new ArrayList<>();
    private Handler handler;
    private int currentIndex;
    private List<ResponseData.MusicInfo> musicInfoList;
    private boolean isPlaying;
    private long currentPlayTime;
    private LoadLyricsTask loadLyricsTask;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        handler = new Handler(Looper.getMainLooper());
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container,
                             @Nullable Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_blank_desc, container, false);
        rvLyrics = root.findViewById(R.id.rv_lyrics);

        layoutManager = new LinearLayoutManager(getContext());
        rvLyrics.setLayoutManager(layoutManager);
        lyricsAdapter = new LyricsAdapter(lyricsLines);
        rvLyrics.setAdapter(lyricsAdapter); // Ensure adapter is set here

        // 尝试从粘性事件中获取初始状态
        MessageEventSeekbar stickyEvent = EventBus.getDefault().getStickyEvent(MessageEventSeekbar.class);
        if (stickyEvent != null) {
            currentIndex = stickyEvent.getCurrentIndex();
            musicInfoList = stickyEvent.getMusicInfoList();
            isPlaying = stickyEvent.getIsPlay();
            currentPlayTime = stickyEvent.getCurrentPosition();
            loadLyrics();
        }

        return root;
    }

    @Subscribe(sticky = true, threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEventSeekbar event) {
        currentIndex = event.getCurrentIndex();
        musicInfoList = event.getMusicInfoList();
        isPlaying = event.getIsPlay();
        currentPlayTime = event.getCurrentPosition();
        loadLyrics();
    }

    private void loadLyrics() {
        if (musicInfoList != null && !musicInfoList.isEmpty()) {
            String lyricUrl = musicInfoList.get(currentIndex).getLyricUrl();
            // 取消之前的任务
            if (loadLyricsTask != null) {
                loadLyricsTask.cancel(true);
            }
            loadLyricsTask = new LoadLyricsTask();
            loadLyricsTask.execute(lyricUrl);
        }
    }

    private class LoadLyricsTask extends AsyncTask<String, Void, List<LyricsLine>> {

        @Override
        protected List<LyricsLine> doInBackground(String... params) {
            String lyricUrl = params[0];
            List<LyricsLine> lyricsLines = new ArrayList<>();
            try (BufferedReader reader = new BufferedReader(new InputStreamReader(new URL(lyricUrl).openStream()))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    if (isCancelled()) {
                        break;
                    }
                    LyricsLine lyricsLine = parseLyricsLine(line);
                    if (lyricsLine != null) {
                        lyricsLines.add(lyricsLine);
                    }
                }
            } catch (IOException e) {
                if (!(e instanceof java.io.InterruptedIOException)) {
                    e.printStackTrace();
                }
            }
            return lyricsLines;
        }

        @Override
        protected void onPostExecute(List<LyricsLine> result) {
            if (!isAdded()) {
                return; // Fragment not attached to activity
            }
            lyricsLines.clear();
            lyricsLines.addAll(result);
            lyricsAdapter.notifyDataSetChanged(); // Update adapter data
            updateLyrics(currentPlayTime);
        }
    }

    private LyricsLine parseLyricsLine(String line) {
        if (line.startsWith("[") && line.contains("]")) {
            int timeEndIndex = line.indexOf("]");
            String timeStr = line.substring(1, timeEndIndex);
            String[] timeParts = timeStr.split(":");
            if (timeParts.length == 2) {
                try {
                    int minutes = Integer.parseInt(timeParts[0]);
                    float seconds = Float.parseFloat(timeParts[1]);
                    long timeInMillis = (long) ((minutes * 60 + seconds) * 1000);
                    String lyrics = line.substring(timeEndIndex + 1);
                    return new LyricsLine(timeInMillis, lyrics);
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    private void updateLyrics(long currentTime) {
        if (lyricsLines != null && !lyricsLines.isEmpty()) {
            LyricsLine currentLyricsLine = getCurrentLyricsLine(currentTime);
            if (currentLyricsLine != null) {
                int currentIndex = lyricsLines.indexOf(currentLyricsLine);
                lyricsAdapter.setCurrentPlayingIndex(currentIndex);
                rvLyrics.smoothScrollToPosition(currentIndex);
                layoutManager.scrollToPositionWithOffset(currentIndex, rvLyrics.getHeight() / 2);
            }
        }
    }

    private LyricsLine getCurrentLyricsLine(long currentTime) {
        LyricsLine previousLine = null;
        for (LyricsLine line : lyricsLines) {
            if (line.time > currentTime) {
                return previousLine;
            }
            previousLine = line;
        }
        return previousLine;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        handler.removeCallbacksAndMessages(null);
        if (loadLyricsTask != null) {
            loadLyricsTask.cancel(true);
        }
    }

    public static class LyricsLine {
        long time;
        public String lyrics;

        LyricsLine(long time, String lyrics) {
            this.time = time;
            this.lyrics = lyrics;
        }
    }
}
